package cn.itmantzy.org.service.impl;

import cn.itmantzy.basic.service.impl.BaseServiceImpl;
import cn.itmantzy.basic.util.MD5Utils;
import cn.itmantzy.basic.util.PageList;
import cn.itmantzy.basic.util.StrUtils;
import cn.itmantzy.org.domain.Employee;
import cn.itmantzy.org.mapper.EmployeeMapper;
import cn.itmantzy.org.query.EmployeeQuery;
import cn.itmantzy.org.service.IEmployeeService;
import cn.itmantzy.user.domain.Logininfo;
import cn.itmantzy.user.mapper.LogininfoMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class EmployeeServiceImpl extends BaseServiceImpl<Employee> implements IEmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private LogininfoMapper logininfoMapper;

    @Override
    public void add(Employee employee){
        // 初始化必要字段
        initEmployee(employee);
        // 拷贝employee中的信息到logininfo中
        Logininfo logininfo = employee2Logininfo(employee);
        logininfoMapper.save(logininfo); // 返回自增id
        employee.setLogininfo_id(logininfo.getId());
        employeeMapper.save(employee);
    }

    private Logininfo employee2Logininfo(Employee employee) {
        Logininfo logininfo = new Logininfo();
        // 同名拷贝原则(属性名相同的拷贝到logininfo对象中)
        BeanUtils.copyProperties(employee, logininfo);
        return logininfo;
    }

    private void initEmployee(Employee employee) {
        // 因为传递的employee对象中没有盐值，密码没有加密，就给盐值进行初始化，并加密密码
        String salt = StrUtils.getComplexRandomString(32);
        String md5Pwd = MD5Utils.encrypByMd5(employee.getPassword() + salt);
        employee.setSalt(salt);
        employee.setPassword(md5Pwd);
    }

}
